package com.ingta.si.web.interceptor;

import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.ingta.si.utils.InitParams;

public class MyHandlerInterceptor extends HandlerInterceptorAdapter {

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
			Object handler) throws Exception {
		// 简单判断，如果要详细控制可以用spring security
		String url = request.getServletPath();
		// System.out.println(request.getRequestURI() + "-------------------"
		// + request.getContextPath() + "--" + url);
		//System.out.println(url.equals("/") + "--" + url);
		if (url.equals("/") || url.startsWith("/login") || url.startsWith("/logout")
				|| url.startsWith("/static")) {
			return true;
		}
		if (request.getSession() != null
				&& request.getSession().getAttribute(InitParams.ADMIN) != null) {
			return true;
		} else {
			// ajax请求
			if ("XMLHttpRequest".equalsIgnoreCase(request.getHeader("X-Requested-With"))
					|| request.getParameter("ajax") != null) {
				PrintWriter out = response.getWriter();
				String timeOutJson = "{\"statusCode\":\"301\",\"message\":\"登录时间超时，请重新登录！\",\"navTabId\":\"\",\"callbackType\":\"\",\"forwardUrl\":login\"\"}";
				out.println(timeOutJson);
			}
		}
		response.sendRedirect(request.getContextPath() + "/login?c=3");
		return false;

	}
	
	public void afterCompletion(
			HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		String pjax=request.getParameter("pjax");
		System.out.println(pjax);
		
	}
}
